package Lesson;

import java.io.*;

public class ObjectTest {
    public void write(Object obj){
        OutputStream out = null;
        ObjectOutputStream objectOut = null;

        try {
            out = new FileOutputStream("obj.txt");
            //创建对象写入流
            objectOut = new ObjectOutputStream(out);
            //将数据写入数据源
            objectOut.writeObject(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                objectOut.close();
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    /**
     *
     * @return 读取的对象
     */
    public Object read(){
        InputStream in = null;
        ObjectInputStream objIn = null;

        try {
            in = new FileInputStream("obj.txt");
            objIn = new ObjectInputStream(in);
            //从数据源中读取对象信息
            Object obj = objIn.readObject();
            return obj;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                objIn.close();
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        ObjectTest test = new ObjectTest();
        test.write(new Student(12,"张三","13887654567"));
        Object obj = test.read();
        System.out.println(obj);
    }
}
